﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using ImageProvider;

namespace ImageLib
{
    public class FileSystemImageProvider : ImageProviderBase
    {
        public ImageCatalogue Root { get; private set; }

        public override Image RetrieveImage(string name, ImageCatalogue catalogue = null)
        {
            catalogue = catalogue ?? this.Root;
            var path = Path.Combine(catalogue.Path, name);
            var image = Image.FromFile(path);
            return image;
        }

        public override IEnumerable<ImageCatalogue> RetrieveCatalogues(ImageCatalogue catalogue = null)
        {
            catalogue = catalogue ?? this.Root;
            var folders = Directory.GetDirectories(catalogue.Path);
            var result = folders.Select(folder => new ImageCatalogue(Path.GetFileName(folder), catalogue)).ToList();
            return result;
        }

        public override void SaveImage(string name, Image image, ImageCatalogue catalogue = null)
        {
            catalogue = catalogue ?? this.Root;
            var path = Path.Combine(catalogue.Path, name);
            image.Save(path, ImageFormat.Png);
        }

        public override ImageCatalogue AddCatalogue(string name, ImageCatalogue parent = null)
        {
            var catalogue = new ImageCatalogue(name, parent ?? this.Root);
            return catalogue;
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);
            var path = this.GetValue<string>(config, "root", root =>
            {
                var cwd = Directory.GetCurrentDirectory();
                try
                {
                    Directory.SetCurrentDirectory(AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
                    root = root ?? ".";
                    if (Directory.Exists(root) == false)
                    {
                        Directory.CreateDirectory(root);
                    }

                    Directory.SetCurrentDirectory(root);
                    root = Directory.GetCurrentDirectory();
                    return root;
                }
                finally
                {
                    Directory.SetCurrentDirectory(cwd);
                }
            });

            this.Root = new ImageCatalogue(path);
        }
    }
}